package fr.awtl.framework;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import fr.awtl.framework.actions.forms.ActionForm;
import fr.awtl.framework.exception.PopulateException;

public class ActionFormFiller {

	@SuppressWarnings("rawtypes")
	Class[] classes = new Class[]{String.class, char.class, float.class, double.class, short.class, long.class, int.class, boolean.class};
	
	public HashMap<String, String[]> populateActionForm(ActionForm actionForm, Map<String, String[]> params) throws PopulateException {

		HashMap<String, String[]> dataFail = new HashMap<String, String[]>();
		
		for (Entry<String, String[]> entry : params.entrySet()) {

			String basic = entry.getKey();
			String value = entry.getValue()[0];
			
			String setField = "set" + basic.substring(0, 1).toUpperCase() + basic.substring(1);

			boolean methodExists = false;
			
			int i = 0;

			while(i<classes.length && !methodExists){
			
				try {
					
					Method m = actionForm.getClass().getMethod(setField, new Class[] { classes[i] });
					Object object=null;
					
					
					switch(i){
					case 0 : object = value; break;
					case 1 : object = value.charAt(0); break;
					case 2 : object = Float.parseFloat(value); break;
					case 3 : object = Double.parseDouble(value); break;
					case 4 : object = Short.parseShort(value); break;
					case 5 : object = Long.parseLong(value); break;
					case 6 : object = Integer.parseInt(value); break;
					case 7 : object = Boolean.parseBoolean(value); break;
					}
					if(object!=null){
						m.invoke(actionForm, new Object[] { object });
						methodExists=true;
					}
				} catch (NoSuchMethodException e) {
				} catch (IllegalAccessException e) {
				} catch (IllegalArgumentException e) {
				} catch (InvocationTargetException e) {
				} 
				i++;
			}
			
			if(!methodExists){
				dataFail.put(entry.getKey(), entry.getValue());
			}
		}

		if (!dataFail.isEmpty()) {

			StringBuffer sb = new StringBuffer();
			for (Entry <String, String[]>i : dataFail.entrySet()) {
				sb.append(i.getKey()+ "  : " + i.getValue()[0] +" - ");
				
			}
			throw new PopulateException("unable to populate the following fields : " + sb);

		} 
		return dataFail;
		
	}

}